// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database({
  throwOnNotFound: false,
})

// 云函数入口函数
exports.main = async (event, context) => {
  let id = event.id
  let selectedSeat = event.selectedSeat
  let orderInfo = event.orderInfo

  try {
    let seat
    let canBuy = true
    const transaction = await db.startTransaction()
    // 先查询选中位置是否是空闲的
    await transaction.collection('session_info').where({
      _id: id
    }).get().then(res => {
      seat = res.data[0].seat
      id = res.data[0]._id
      for (let i in selectedSeat) {
        let x = selectedSeat[i][0]
        let y = selectedSeat[i][1]
        if (seat[x][y] !== 1) {
          canBuy = false
        }
        seat[x][y] = 0
      }
    })

    if (!canBuy) {
      return {
        line: 37,
        status: false,
      }
    }

    await transaction.collection('session_info').doc(id).update({
      data: {
        seat: seat
      }
    })

    await transaction.collection('order_info').add({
      data: {
        lastname: orderInfo.lastname,
        phone: orderInfo.phone,
        price: orderInfo.price,
        orderDate: orderInfo.orderDate,
        movieId: orderInfo.movieId,
        movieName: orderInfo.movieName,
        orderSessionId: orderInfo.orderSessionId,
        seat: orderInfo.seat,
        _openid: orderInfo.openid
      }
    })

    await transaction.commit()
  } catch(e) {
    console.error(`transaction error: ${e}`)
    return {
      line: 66,
      status: false,
      err: e
    }
  }
  return {
    status: true
  }
}